package framework.beans;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateEditor extends PropertyEditorSupport {
    private final String formatPattern;
    private final boolean allowEmpty;

    public CustomDateEditor(String formatPattern, boolean allowEmpty) {
        this.formatPattern = formatPattern;
        this.allowEmpty = allowEmpty;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (allowEmpty && text.isEmpty()) {
            setValue(null);
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat(this.formatPattern);
            dateFormat.setLenient(false);
            try {
                setValue(dateFormat.parse(text));
            } catch (ParseException e) {
                throw new IllegalArgumentException("Invalid date format", e);
            }
        }
    }

    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        SimpleDateFormat dateFormat = new SimpleDateFormat(this.formatPattern);
        dateFormat.setLenient(false);
        return (value != null ? dateFormat.format(value) : "");
    }
}